package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    /**
     * 员工登录
     * @param emp
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("登录：emp={}", emp);
        //1.调用service的登录方法, 获取返回结果
        Emp e = empService.login(emp);

        //登录成功就生成JWT令牌
        if (e != null) {
            Map<String, Object> claim = new HashMap<>();
            claim.put("id", e.getId());
            claim.put("username", e.getUsername());
            String token = JwtUtils.generateJwt(claim);
            //将生成的令牌返回给前端
            return Result.success(token);
        }

        //2.响应
        return Result.error("用户名或密码不匹配！！！");
    }

    @GetMapping("/exit")
    public void exit(){
        System.out.println("优雅停机~");
        System.exit(0);
    }
}
